<template>
  <div class="el-tree-select-container">
    <el-select
      :value="selectedName"
      :placeholder="placeholder"
      :clearable="clearable"
      @clear="handleClear"
      @visible-change="handleVisibleChange"
      ref="select"
      filterable
      :filter-method="handleFilter"
      :popper-append-to-body="false"
      @input="handleSelectInput"
    >
      <!-- 树形结构 -->
      <el-option value="" class="el-tree-select-option">
        <el-input
          v-model="searchQuery"
          placeholder="搜索节点..."
          class="search-input"
          @input="handleSearch"
        ></el-input>

        <el-tree
          :data="filteredTreeData"
          :props="treeProps"
          :node-key="nodeKey"
          :default-expanded-keys="defaultExpandedKeys"
          :current-node-key="currentValue"
          @node-click="handleNodeClick"
          ref="tree"
          highlight-current
        ></el-tree>
      </el-option>
    </el-select>
  </div>
</template>

<script>
export default {
  name: "ElTreeSelect",
  props: {
    data: {
      type: Array,
      default: () => [],
    },
    placeholder: {
      type: String,
      default: "请选择...",
    },
    clearable: {
      type: Boolean,
      default: true,
    },
    // v-model绑定的是ID
    value: {
      type: String,
      default: "",
    },
    nodeKey: {
      type: String,
      default: "id",
    },
  },
  data() {
    return {
      treeData: [],
      filteredTreeData: [],
      searchQuery: "",
      // 当前选中的ID
      currentValue: this.value,
      // 用于显示的选中名称
      selectedName: "",
      treeProps: {
        children: "children",
        label: "name",
      },
      defaultExpandedKeys: [],
    };
  },
  watch: {
    data: {
      immediate: true,
      handler(newData) {
        this.treeData = this.buildTree(newData);
        this.filteredTreeData = [...this.treeData];
        this.updateSelectedName();
      },
    },
    // 监听v-model传入的ID变化
    value: {
      immediate: true,
      handler(newVal) {
        this.currentValue = newVal;
        this.updateSelectedName();
      },
    },
    // 当选中ID变化时，更新显示名称并通知父组件
    currentValue(newVal) {
      this.updateSelectedName();
      this.$emit("input", newVal);
      this.$emit("change", newVal);
    },
  },
  methods: {
    buildTree(data) {
      const nodeMap = {};
      const tree = [];

      data.forEach((node) => {
        nodeMap[node[this.nodeKey]] = { ...node, children: [] };
      });

      data.forEach((node) => {
        const currentNode = nodeMap[node[this.nodeKey]];
        if (node.pid === "0") {
          tree.push(currentNode);
        } else {
          const parentNode = nodeMap[node.pid];
          if (parentNode) {
            parentNode.children.push(currentNode);
          }
        }
      });

      return tree;
    },

    // 根据ID更新显示的名称
    updateSelectedName() {
      if (!this.currentValue) {
        this.selectedName = "";
        return;
      }

      const node = this.findNodeById(this.treeData, this.currentValue);
      this.selectedName = node ? node.name : "";
    },

    findNodeById(nodes, id) {
      for (const node of nodes) {
        if (node[this.nodeKey] === id) {
          return node;
        }
        if (node.children && node.children.length) {
          const found = this.findNodeById(node.children, id);
          if (found) return found;
        }
      }
      return null;
    },

    handleNodeClick(node) {
      const nodeId = node[this.nodeKey];
      this.currentValue = nodeId;
      this.selectedName = node.name;
      this.$refs.select.blur();
      this.searchQuery = "";
      this.filteredTreeData = [...this.treeData];
    },

    handleSearch() {
      if (!this.searchQuery) {
        this.filteredTreeData = [...this.treeData];
        this.defaultExpandedKeys = [];
        return;
      }

      const filteredNodes = [];
      const expandedKeys = new Set();

      const filterNode = (nodes, parentMatched = false) => {
        return nodes.reduce((acc, node) => {
          const nodeMatched = node.name
            .toLowerCase()
            .includes(this.searchQuery.toLowerCase());
          const childrenMatched =
            node.children &&
            filterNode(node.children, parentMatched || nodeMatched).length > 0;

          if (nodeMatched || parentMatched || childrenMatched) {
            const newNode = { ...node };
            if (node.children) {
              newNode.children = filterNode(
                node.children,
                parentMatched || nodeMatched
              );
            }
            acc.push(newNode);

            if (nodeMatched || childrenMatched) {
              expandedKeys.add(node[this.nodeKey]);
            }
          }

          return acc;
        }, []);
      };

      this.filteredTreeData = filterNode(this.treeData);
      this.defaultExpandedKeys = Array.from(expandedKeys);
    },

    handleFilter(query) {
      this.searchQuery = query;
      this.handleSearch();
    },

    handleClear() {
      this.currentValue = "";
      this.selectedName = "";
      this.searchQuery = "";
      this.filteredTreeData = [...this.treeData];
      this.defaultExpandedKeys = [];
      this.$emit("clear");
      this.$emit("input", "");
    },

    handleVisibleChange(visible) {
      if (!visible) {
        this.searchQuery = "";
        this.filteredTreeData = [...this.treeData];
        this.defaultExpandedKeys = [];
      } else {
        if (this.currentValue) {
          this.expandToSelectedNode();
        }
      }
      this.$emit("visible-change", visible);
    },

    expandToSelectedNode() {
      if (!this.currentValue) return;

      const getAncestorIds = (node, targetId, ancestors = []) => {
        if (node[this.nodeKey] === targetId) {
          return [...ancestors, node[this.nodeKey]];
        }

        if (node.children && node.children.length) {
          for (const child of node.children) {
            const result = getAncestorIds(child, targetId, [
              ...ancestors,
              node[this.nodeKey],
            ]);
            if (result) return result;
          }
        }

        return null;
      };

      for (const node of this.treeData) {
        const ancestorIds = getAncestorIds(node, this.currentValue);
        if (ancestorIds) {
          this.defaultExpandedKeys = ancestorIds.slice(0, -1);
          break;
        }
      }
    },

    // 处理select输入事件（主要用于清空）
    handleSelectInput(val) {
      if (!val) {
        this.handleClear();
      }
    },
  },
};
</script>

<style scoped>
.el-tree-select-container {
  width: 100%;
  max-width: 300px;
}

.search-input {
  padding: 8px 10px;
  margin: 5px;
  width: calc(100% - 10px);
}

.el-tree-select-option {
  padding: 0;
  height: auto;
  max-height: 300px;
  overflow-y: auto;
}

::v-deep .el-select-dropdown__item {
  padding: 0;
}

::v-deep .el-tree-node__content {
  height: auto;
  padding: 6px 10px;
}

/* 确保显示名称正常显示 */
::v-deep .el-select__input {
  display: none;
}

::v-deep .el-select__tags {
  max-width: 100%;
}
</style>
